﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;

public partial class Modules_Flow_FlowList : System.Web.UI.Page
{

    IPerf_FlowHandler flowHandler = new Perf_FlowManage();

    IPerf_Flow_StepsHandler flowStepHandler = new Perf_Flow_StepsManage();
    IPerf_Flow_TraceHandler flowTraceHandler = new Perf_Flow_TraceManage();
    DataBase db = new DataBase();
    ISys_OrganizationHandler orgHandler = new Sys_OrganizationManage();
    ISys_RoleHandler roleHandler = new Sys_RoleManage();
    ISys_UserHandler userHandler = new Sys_UserManage();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPurviews())
        {
            Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            ViewState["OrderBy"] = "Id";
            ViewState["Accending"] = "desc";

            ViewState["OrderByStep"] = "Step_Num";
            ViewState["AccendingStep"] = "asc";

            dataBind(string.Empty, null);

        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("401000"))
            {
                //if (strPur.Contains("401010"))
                //{
                //    btnCreate.Visible = true;
                //}
                //else
                //{
                //    btnCreate.Visible = false;
                //}
            }
            else
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 初始化流程管理信息表
    /// </summary>
    private void dataBind(string whereClause, SqlParameter[] parms)
    {
        try
        {
            SqlParameter[] parms2 = null;
            int counter = 0;
            DataTable dt = new DataTable();

            if (whereClause != string.Empty)
            {
                whereClause += " and IsEnable=1 ";
                dt = flowHandler.GetPerf_FlowByPageList(whereClause, parms, ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                whereClause = "1=1";
                ProcessParms(ref whereClause, ref parms2);
                counter = flowHandler.GetCounter(whereClause, parms2);
            }
            else
            {
                dt = flowHandler.GetPerf_FlowByPageList("IsEnable=1 ", null, ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                counter = flowHandler.GetCounter("IsEnable=@IsEnable", new SqlParameter[] { new SqlParameter("@IsEnable", "1") });
            }

            this.AspNetPager.RecordCount = counter;
            gvFlowList.DataSource = dt;
            gvFlowList.DataBind();

            divFlow.Style.Add("display", "block");
            divStep.Style.Add("display", "none");
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string whereClause, ref SqlParameter[] parms)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();


        if (ViewState["Name"] != null)
        {
            whereClause += " and Name  like + '%' + @Name + '%'";
            lstParm.Add(new SqlParameter("@Name", ViewState["Name"].ToString()));
        }

        if (ViewState["Code"] != null)
        {
            whereClause += " and Code like + '%' + @Code + '%'";
            lstParm.Add(new SqlParameter("@Code", ViewState["Code"].ToString()));
        }

        parms = lstParm.ToArray();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (txtCode.Text != string.Empty)
            ViewState["Code"] = txtCode.Text.Trim();
        else
            ViewState["Code"] = null;

        if (txtName.Text != string.Empty)
            ViewState["Name"] = txtName.Text.Trim();
        else
            ViewState["Name"] = null;

        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParms(ref clause, ref parms);
        dataBind(clause, parms);
    }

    protected void gvFlowList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //
        //if (e.CommandName == "del")
        //{
        //    int id = Convert.ToInt32(e.CommandArgument.ToString().Trim());
        //    try
        //    {
        //        //如果当前流程过程跟踪表还有该流程没有结束的不能删除
        //        DataTable dtTrace = flowTraceHandler.GetPerf_Flow_TraceList("Flow_ID=@FlowID and Status=@Status", new SqlParameter[] { new SqlParameter("@FlowID", id.ToString()), new SqlParameter("@Status", Enums.FlowStatus.Doing.ToString("d")) });
        //        if (dtTrace != null && dtTrace.Rows.Count > 0)
        //        {
        //            Jscript.AlertInAjax("删除失败!该流程正在进行中!", UpdatePanel1);
        //            return;
        //        }
        //        else
        //        {
        //            Perf_FlowQuery query = flowHandler.GetPerf_FlowQuery(id);
        //            if (query != null)
        //            {
        //                query.IsEnable = int.Parse(Enums.NormalStatus.Invalid.ToString("d"));
        //                if (flowHandler.UpdatePerf_Flow(query))
        //                {
        //                    //删除相应步骤

        //                    string SqlStr = @"update Perf_Flow_Steps set IsEnable=@IsEnable where Flow_ID=@FlowID";

        //                    db.ExecSqlsTransaction(SqlStr, new SqlParameter[] { new SqlParameter("@IsEnable", Enums.NormalStatus.Vallid.ToString("d")), new SqlParameter("@FlowID", id.ToString()) });

        //                    Jscript.AlertInAjax("操作成功!", UpdatePanel1);
        //                    dataBind(string.Empty, null);
        //                }
        //                else
        //                {
        //                    Jscript.AlertInAjax("操作失败!", UpdatePanel1);

        //                }
        //            }
        //        }
        //    }
        //    catch
        //    {
        //        Jscript.AlertInAjax("操作失败!", UpdatePanel1);
        //    }
        //}
        //else if(e.CommandName == "reload")
        //{
        //    SqlParameter[] parms = null;
        //    string clause = " 1=1 ";
        //    ProcessParms(ref clause, ref parms);
        //    dataBind(clause, parms);
        //}
         if (e.CommandName == "step")
        {
            ViewState["FlowID"] = e.CommandArgument.ToString();
            hidFlowID.Value = e.CommandArgument.ToString();
            dataBindStep(string.Empty,null, int.Parse(e.CommandArgument.ToString()));
        }
    }

    protected void gvFlowList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
           // ImageButton ibtnDel = (ImageButton)e.Row.FindControl("ibtnDelete");
            ImageButton ibtnStep = (ImageButton)e.Row.FindControl("ibtnStep");
            //if (Session["UserPurviews"] != null)
            //{
            //    if (Session["UserPurviews"].ToString().Contains("401020"))//删除
            //    {
            //        ibtnDel.Visible = true;
            //    }
            //    else
            //    {
            //        ibtnDel.Visible = false;
            //    }
            //}

            if (Session["UserPurviews"] != null)
            {
                if (Session["UserPurviews"].ToString().Contains("401031"))//步骤管理
                {
                    ibtnStep.Visible = true;
                }
                else
                {
                    ibtnStep.Visible = false;
                }
            }


        }
    }

    protected void gvFlowList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParms(ref clause, ref parms);
        dataBind(clause, parms);
    }


    protected void CreateButton_Click(object sender, EventArgs e)
    {
        dataBind(string.Empty, null);
    }
    protected void AspNetPager_PageChanged(object src, EventArgs e)
    {
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParms(ref clause, ref parms);
        dataBind(clause, parms);
    }


    #region FlowStep

    private bool CheckStepPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("401000"))
            {
                if (strPur.Contains("401021"))
                {
                    btnCreateStep.Visible = true;
                }
                else
                {
                    btnCreateStep.Visible = false;
                }
            }
            else
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }


    private void dataBindStep(string whereClause, SqlParameter[] parms,int flowID)
    {

        try
        {
            if (!CheckStepPurviews())
            {
                Response.Redirect("~/Login.aspx");
            }

            SqlParameter[] parms2 = null;
            int counter = 0;
            DataTable dtStep = new DataTable();

            if (whereClause != string.Empty)
            {
                whereClause += " and IsEnable=1 and Flow_ID=" +flowID;
                dtStep = flowStepHandler.GetPerf_Flow_StepsByPageList(whereClause, parms, ViewState["OrderByStep"].ToString() + " " + ViewState["AccendingStep"].ToString(), AspNetPager1.StartRecordIndex - 1, AspNetPager1.PageSize);
                                    
                ProcessParmsStep(ref whereClause, ref parms2);
                counter = flowStepHandler.GetCounter(whereClause, parms2);
            }
            else
            {
                dtStep = flowStepHandler.GetPerf_Flow_StepsByPageList("  IsEnable=@IsEnable and Flow_ID=@FlowID", new SqlParameter[] { new SqlParameter("@IsEnable",Enums.NormalStatus.Vallid.ToString("d")),new SqlParameter("@FlowID",flowID.ToString())}, ViewState["OrderByStep"].ToString() + " " + ViewState["AccendingStep"].ToString(), AspNetPager1.StartRecordIndex - 1, AspNetPager1.PageSize);
                counter = flowHandler.GetCounter("  IsEnable=@IsEnable and Flow_ID=@FlowID", new SqlParameter[] { new SqlParameter("@IsEnable", "1"),new SqlParameter("@FlowID",flowID.ToString()) });
            }

            this.AspNetPager1.RecordCount = counter;
            gvStepList.DataSource = dtStep;
            gvStepList.DataBind();

            divFlow.Style.Add("display", "none");
            divStep.Style.Add("display", "block");
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
             
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessParmsStep(ref string whereClause, ref SqlParameter[] parms)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();


        if (ViewState["StepName"] != null)
        {
            whereClause += " and StepName  like + '%' + @StepName + '%'";
            lstParm.Add(new SqlParameter("@StepName", ViewState["StepName"].ToString()));
        }
        parms = lstParm.ToArray();
    }



    public string GetRole(object id)
    {
        string name = string.Empty;
        Perf_Flow_StepsQuery query = flowStepHandler.GetPerf_Flow_StepsQuery(int.Parse(id.ToString()));
        if (query != null)
        {
            if (query.Approve_Way.ToString() == Enums.ApproveWay.Role.ToString("d"))
            {
                Sys_RoleQuery rQuery = roleHandler.GetSys_RoleQuery(query.Role_ID);
                if (rQuery != null)
                {
                    name = rQuery.Name;
                }                
            }
            else if (query.Approve_Way.ToString() == Enums.ApproveWay.DepartMent.ToString("d"))
            {
                Sys_OrganizationQuery oQuery = orgHandler.GetSys_OrganizationQuery(query.Org_ID);
                if (oQuery != null)
                {
                    name = oQuery.Name;
                }
            }
            else if (query.Approve_Way.ToString() == Enums.ApproveWay.Personal.ToString("d"))
            {
                Sys_UserQuery uquery = userHandler.GetSys_UserQuery(query.User_ID);
                if (uquery != null)
                {
                    name = uquery.Name;
                }
            }

        }
        return name;
    }


    public void LBtnBack_Click(object sender, EventArgs e)
    {
        divFlow.Style.Add("display", "block");
        divStep.Style.Add("display", "none");

        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParms(ref clause, ref parms);
        dataBind(clause, parms);
    }

    public void btnStepSearch_Click(object sender, EventArgs e)
    {
        if (txtStepName.Text != string.Empty)
        {
            ViewState["StepName"] = txtStepName.Text.Trim();
        }
        else
        {
            ViewState["StepName"] = null;
        }

        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParmsStep(ref clause, ref parms);
        dataBindStep(clause, parms, int.Parse(ViewState["FlowID"].ToString()));
    }

    public void btnCreateStep_Click(object sender, EventArgs e)
    {
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParmsStep(ref clause, ref parms);
        dataBindStep(clause, parms, int.Parse(ViewState["FlowID"].ToString()));
    }

    protected void gvStepList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParmsStep(ref clause, ref parms);
        dataBindStep(clause, parms,int.Parse(ViewState["FlowID"].ToString()));
    }


    protected void gvStepList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ImageButton ibtnDel = (ImageButton)e.Row.FindControl("ibtnDeletes");

            if (Session["UserPurviews"] != null)
            {
                if (Session["UserPurviews"].ToString().Contains("401030"))//删除
                {
                    ibtnDel.Visible = true;
                }
                else
                {
                    ibtnDel.Visible = false;
                }
            }


        }
    }

  
    protected void gvStepList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "edt")
        {
            SqlParameter[] parms = null;
            string clause = " 1=1 ";
            ProcessParmsStep(ref clause, ref parms);
            dataBindStep(clause, parms, int.Parse(ViewState["FlowID"].ToString()));
        }
        else if (e.CommandName == "del")
        {
            Perf_Flow_StepsQuery query = flowStepHandler.GetPerf_Flow_StepsQuery(int.Parse(e.CommandArgument.ToString()));
            if(query !=null)
            {
                Perf_Flow_StepsQuery[] stepQuery = flowStepHandler.GetPerf_Flow_StepsQueryList("Flow_ID=@FlowID and IsEnable=@IsEnable", new SqlParameter[] { new SqlParameter("@FlowID",ViewState["FlowID"].ToString()),new SqlParameter("@IsEnable",Enums.NormalStatus.Vallid.ToString("d"))}," ID asc");
                if (stepQuery != null && stepQuery.Length > 0)
                {
                   for(int i=0;i<stepQuery.Length;i++)
                   {
                        //删除的是第一个步骤
                       if (query.ID.ToString().Equals(stepQuery[0].ID.ToString()))
                        {
                            if (stepQuery.Length > 1)
                            {
                                stepQuery[1].Prev_ID = 0;
                                flowStepHandler.UpdatePerf_Flow_Steps(stepQuery[1]);
                            }                        
                            break;
                        }
                        else if (query.ID.ToString().Equals(stepQuery[stepQuery.Length - 1].ID.ToString()))//最后一步
                        {

                            if (stepQuery.Length > 1)
                            {
                                stepQuery[stepQuery.Length - 2].Next_ID = 0;
                                flowStepHandler.UpdatePerf_Flow_Steps(stepQuery[stepQuery.Length - 2]);
                            }
                            break;
                        }
                        else
                        {
                            if (stepQuery.Length > 1)
                            {
                                if (query.ID.ToString().Equals(stepQuery[i].ID.ToString()))
                                {
                                    stepQuery[i - 1].Next_ID = stepQuery[i + 1].ID;
                                    flowStepHandler.UpdatePerf_Flow_Steps(stepQuery[i - 1]);

                                    stepQuery[i + 1].Prev_ID = stepQuery[i - 1].ID;
                                    flowStepHandler.UpdatePerf_Flow_Steps(stepQuery[i + 1]);
                                }
                            }
                        }

                    }
                    query.IsEnable = int.Parse(Enums.NormalStatus.Invalid.ToString("d"));

                    if (flowStepHandler.UpdatePerf_Flow_Steps(query))
                    {
                        SqlParameter[] parms = null;
                        string clause = " 1=1 ";
                        ProcessParmsStep(ref clause, ref parms);
                        dataBindStep(clause, parms, int.Parse(ViewState["FlowID"].ToString()));
                    }
                }
            }
        }
    }

    protected void AspNetPager1_PageChanged(object src, EventArgs e)
    {
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParmsStep(ref clause, ref parms);
        dataBindStep(clause, parms,int.Parse(ViewState["FlowID"].ToString()));
    }

    #endregion


}
